const errorType = require('../constants/error-types')
const service = require('../service/user.service')
const md5password = require('../utils/password-handle')
const verifyUser = async (ctx, next) => {
  //1.判断前端账号密码用户名是否输入完整
  const { account, password, name } = ctx.request.body;
  if (!account || !password || !name) {
    const error = new Error(errorType.NAME_OR_PASSWORD_OR_ACCOUNT_IS_REQUIRED);
    return ctx.app.emit('error', error, ctx);
  }
  //2.判断该账号是否被注册，如果已注册则抛出异常。
  const result = await service.getUserByAccount(account);
  if (result.length != 0) {
    const error = new Error(errorType.ACCOUNT_NUMBER_ALREADY_EXISTS);
    return ctx.app.emit('error', error, ctx);
  }
  await next()
}

  const handlePassword = async (ctx,next)=>{
    let {password} = ctx.request.body;
    ctx.request.body.password = md5password(password);
    await next()
  }


module.exports = {
  verifyUser,
  handlePassword
}